import { reactive, ref } from 'vue'
import { defineStore } from 'pinia'
import { USER_INFO, REMEMBER_ME, TOKEN, USERNAME, PASSWORD, BUTTON } from '@/config/constants'
import { useRouter, useRoute } from 'vue-router'
import { logout, login } from '@/api/login'
import { Message } from '@arco-design/web-vue'
import { useI18n } from 'vue-i18n'
import { useRoutesStore } from './router'
export const useUserStore = defineStore('user', () => {
  const { t } = useI18n()
  const router = useRouter()
  const route = useRoute()
  const { resetRouterStore } = useRoutesStore()
  let currenUser = reactive(JSON.parse(localStorage.getItem(USER_INFO)) || {})
  const token = ref(localStorage.getItem(USER_INFO))
  const rememberMe = ref(JSON.parse(localStorage.getItem(REMEMBER_ME)) || false)

  const doLogin = (data) => {
    return new Promise((resolve, reject) => {
      login(data)
        .then((res) => {
          if (res.code === 200) {
            const userInfo = res.data
            Message.success(t('login.loginSuccess'))
            router.replace(route.query.redirect || '/dashboard')
            localStorage.setItem(USER_INFO, JSON.stringify(userInfo))
            localStorage.setItem(TOKEN, userInfo.token)
            currenUser = userInfo
            token.value = userInfo.token
            if (rememberMe.value) {
              localStorage.setItem(USERNAME, data.username)
              localStorage.setItem(PASSWORD, data.password)
            } else {
              localStorage.removeItem(USERNAME)
              localStorage.removeItem(PASSWORD)
            }
          } else {
            Message.error(res.message)
          }
          resolve(res)
        })
        .catch((e) => {
          reject(e)
        })
    })
  }

  const doLogout = () => {
    return new Promise((resolve, reject) => {
      logout({ token: token.value })
        .then((res) => {
          if (res.code === 200) {
            Message.success(t('login.logoutSuccess'))
            router.replace('/login')
            localStorage.removeItem(TOKEN)
            localStorage.removeItem(BUTTON)
            resetRouterStore()
          } else {
            Message.error(res.message)
          }
          resolve(res)
        })
        .catch((e) => {
          reject(e)
        })
    })
  }

  const changeRemember = (value) => {
    console.log(value)
    rememberMe.value = value
    localStorage.setItem(REMEMBER_ME, value)
  }

  return { currenUser, rememberMe, token, doLogin, doLogout, changeRemember }
})
